package com.huizhan.web.view;

import java.io.*;
import java.math.*;
import java.net.*;
import java.security.*;
import java.util.*;
import org.apache.commons.codec.binary.Base64;
import java.awt.image.*;
import javax.imageio.ImageIO;
/**
 * 工具类
 */
public  class Util {  

    public static void base64ToImage(String base64String,String fileName) {
        try { 
            byte[] bytes1 = Base64.decodeBase64(base64String);
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
            BufferedImage bi1 = ImageIO.read(bais);
            File f1 = new File(fileName);
            ImageIO.write(bi1, "jpg", f1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void base64ToFile(String base64, String fileName) {
        File file = null;
        BufferedOutputStream bos = null;
        java.io.FileOutputStream fos = null;
        try {
            
            byte[] bytes = Base64.decodeBase64(base64);
            file=new File(fileName);
            fos = new java.io.FileOutputStream(file);
            
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static String fileToBase64(String path) {
        String base64 = null;
        InputStream in = null;
        try {
            File file = new File(path);
            in = new FileInputStream(file);
            byte[] bytes = new byte[in.available()];
            base64 = Base64.encodeBase64String(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return base64;
    }

    public static String doGet(String urlPath) throws Exception {
        URL url = new URL(urlPath);
        HttpURLConnection conn = (HttpURLConnection) 
        url.openConnection();
        conn.setConnectTimeout(5000); 
        conn.setRequestMethod("GET");

        if (conn.getResponseCode() == 200) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder sbs = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sbs.append(line);
            }
            return sbs.toString();
        }

        return null;
    }

    public static String doGet(String urlPath, HashMap<String, Object> params)throws Exception {
        StringBuilder sb = new StringBuilder(urlPath);
        if (params != null && !params.isEmpty()) { // 说明有参数
            sb.append("?");
            Set<Map.Entry<String, Object>> set = params.entrySet();
            for (Map.Entry<String, Object> entry : set) { // 遍历map里面的参数
                String key = entry.getKey();
                String value = "";
                if (null != entry.getValue()) {
                    value = entry.getValue().toString();
                    value = URLEncoder.encode(value, "UTF-8");
                }
                sb.append(key).append("=").append(value).append("&");
            }

            sb.deleteCharAt(sb.length() - 1); 
        }

        URL url = new URL(sb.toString());
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5000); 
        conn.setRequestMethod("GET");

        if (conn.getResponseCode() == 200) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder sbs = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sbs.append(line);
            }
            return sbs.toString();
        }

        return null;
    }

    /**
     * 获取文件后缀名
     * @param fileName 文件
     * @return 后缀
     */
    public static String getFileSuffix(String fileName){
       return fileName.substring(fileName.lastIndexOf("."));
    }

    /**     
     * java获取文件的md5值       
     * @param fis 输入流     
     * @return     
     */    
    public static String md5HashCode(InputStream fis) {       
        try {          
            //拿到一个MD5转换器,如果想使用SHA-1或SHA-256，则传入SHA-1,SHA-256              
            MessageDigest md = MessageDigest.getInstance("MD5");                         
            //分多次将一个文件读入，对于大型文件而言，比较推荐这种方式，占用内存比较少。         
            byte[] buffer = new byte[1024];             
            int length = -1;            
            while ((length = fis.read(buffer, 0, 1024)) != -1) {        
                md.update(buffer, 0, length);            
            }              
            fis.close();           
            //转换并返回包含16个元素字节数组,返回数值范围为-128到127  	
            byte[] md5Bytes  = md.digest();         
            BigInteger bigInt = new BigInteger(1, md5Bytes);//1代表绝对值     
            return bigInt.toString(16);//转换为16进制       
        } catch (Exception e) {       
            e.printStackTrace();   
            return "";    
        }     
    }        
                     
    public static InputStream base64ToInputStream(String base64) {

        byte[] bytes = new byte[1024];

        try {
             bytes = Base64.decodeBase64(base64);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new ByteArrayInputStream(bytes);
    }

    /**     
     * java计算文件32位md5值     
     * @param fis 输入流     
     * @return     
    */  	
    public static String md5HashCode32(InputStream fis) {  		
        try {  		
                //拿到一个MD5转换器,如果想使用SHA-1或SHA-256，则传入SHA-1,SHA-256    
                MessageDigest md = MessageDigest.getInstance("MD5");  			  
                //分多次将一个文件读入，对于大型文件而言，比较推荐这种方式，占用内存比较少。  	
                byte[] buffer = new byte[1024];  		
                int length = -1;  		
                while ((length = fis.read(buffer, 0, 1024)) != -1) {  		
                    md.update(buffer, 0, length);  		
                }  			
                fis.close();  		
                //转换并返回包含16个元素字节数组,返回数值范围为-128到127 
                byte[] md5Bytes  = md.digest();  	
                StringBuffer hexValue = new StringBuffer();  	
                for (int i = 0; i < md5Bytes.length; i++) {  	
                    int val = ((int) md5Bytes[i]) & 0xff;//解释参见最下方
                    if (val < 16) {  				
                        /** * 如果小于16，那么val值的16进制形式必然为一位，* 因为十进制0,1...9,10,11,12,13,14,15 对应的 16进制为 0,1...9,a,b,c,d,e,f;* 此处高位补0。 */  			
                        hexValue.append("0");  				
                    }  			
                    //这里借助了Integer类的方法实现16进制的转换   			
                    hexValue.append(Integer.toHexString(val));  		
                }  			
                return hexValue.toString();  	
        } catch (Exception e) {  			
            e.printStackTrace();  			
            return "";  	
        }  
    }

}